package cn.tedu.xyh.controller;



import cn.tedu.xyh.entity.User;
import cn.tedu.xyh.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired
    UserMapper mapper;
    @RequestMapping("/reg")
    public int reg(@RequestBody User user){
        System.out.println("user = " + user);
        User u = mapper.selectUsername(user.getUsername());
        if (u != null){
            return 2;//代表用户名已存在
        }
        mapper.insert(user);
      return 1;
    }
    @RequestMapping("/login")
    public int login(@RequestBody User user, HttpSession session){
        System.out.println("user = " + user);
        User u = mapper.selectUsername(user.getUsername());
        if (u!=null){
            if (user.getPassword().equals(u.getPassword())){
                //把当前登录的用户对象保存到会话对象中
                //user代表用户输入的信息包括:用户名和密码
                //u代表从数据库中查询到的信息 包括 id 用户名和密码 昵称
                session.setAttribute("user",u);
                return 1;//登录成功
            }
            return 3;//密码错误
        }
        return 2;//用户不存在
    }
    @RequestMapping("/currentUser")
    public User currentUser(HttpSession session){
        //从会话对象中得到登录成功时保存的用户对象
        User u = (User) session.getAttribute("user");
        return u;
    }
    @RequestMapping("/logout")
    public void logout(HttpSession session){
        //把登录成功时保存的user对象删除
        session.removeAttribute("user");
    }

}
